package com.qinsilk.axon.inventory.query

import com.qinsilk.axon.inventory.command.*
import org.axonframework.eventhandling.EventHandler
import org.springframework.stereotype.Component

@Component
class InventoryEventHandler(private val inventoryRepository: InventoryRepository) {

    @EventHandler
    fun on(event: InventoryCreatedEvent) {
        val model =
                InventoryQueryModel(
                        event.inventoryId,
                        event.productName,
                        event.initialQuantity,
                        "创建库存"
                )
        inventoryRepository.save(model)
    }

    @EventHandler
    fun on(event: StockInRecordedEvent) {
        val model = inventoryRepository.findById(event.inventoryId).orElse(null)
        if (model != null) {
            model.quantity += event.quantity
            model.lastEvent = "入库: ${event.reason}"
            inventoryRepository.save(model)
        }
    }

    @EventHandler
    fun on(event: StockOutRecordedEvent) {
        val model = inventoryRepository.findById(event.inventoryId).orElse(null)
        if (model != null) {
            model.quantity -= event.quantity
            model.lastEvent = "出库: ${event.reason}"
            inventoryRepository.save(model)
        }
    }

    @EventHandler
    fun on(event: OperationCancelledEvent) {
        val model = inventoryRepository.findById(event.inventoryId).orElse(null)
        if (model != null) {
            when (event.eventType) {
                "StockInRecordedEvent" -> {
                    model.quantity -= event.quantity
                    model.lastEvent = "撤销入库操作"
                }
                "StockOutRecordedEvent" -> {
                    model.quantity += event.quantity
                    model.lastEvent = "撤销出库操作"
                }
            }
            inventoryRepository.save(model)
        }
    }
}
